<?php
namespace Destroyer\Http\Requests;

use Closure;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Rule;
use Illuminate\Support\Fluent;
use Destroyer\Models\Role;

class RoleUpdateRequest extends FormRequest
{

    protected $stopOnFirstFailure = false;

    public function rules(): array
    {

        $unique = Rule::unique(Role::class)->ignore($this->route('id'));

        return [
            'name'     => ['sometimes', 'alpha_num', 'between:2,50', $unique],
            'code'     => ['sometimes', 'alpha_num:ascii', 'between:2,50', $unique],
            'sort'     => ['sometimes', 'integer', 'between:0,65535'],
            'status'   => [
                'sometimes', 
                'boolean',
                Closure::fromCallable([$this, 'validateStatus'])
            ],
            // 附加字段
            'menu_ids'   => ['nullable', 'array'],
            'menu_ids.*'   => ['sometimes', 'integer', 'exists:system_menu,id'],
        ];
    }

    public function attributes()
    {
        return [
            'name'   => '角色名称',
            'code'   => '权限字符',
            'sort'   => '排序',
            'status' => '状态',
        ];
    }

    public function messages()
    {
        return [
            'name.unique' => ':attribute `:input` 已经存在',
            'code.unique' => ':attribute `:input` 已经存在',
        ];
    }

    public function withValidator($validator)
    {

    }

    public function validateStatus(string $attribute, mixed $value, Closure $fail)
    {
        if( $this->route('id') == 1 && $value != 1 ){
            $fail("超级管理员不可被禁用");
        }
    }
}
